<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/18
 * Time: 11:23
 */

namespace app\admin\controller;

use think\Db;
use think\Validate;

class Ad extends Base
{
    public function index()
    {
        $num = Db::name('ad_position')
            ->count();
        $pageObject = new \Page($num);

        $list = Db::name('ad_position')
            ->select();
        $map = array(
            'num' => $num,
            'list' => $list,
            'page' => $pageObject->getPages()
        );

        return view('index', $map);
    }

    public function add()
    {
        $validate = new Validate([
            ['name', 'require|unique:ad_position', '广告位置必填|广告位置重复'],
            ['width', 'require', '广告宽度必填'],
            ['height', 'require', '广告高度必填'],
        ]);
        if (!$validate->check($_POST)) {
            $this->error($validate->getError());
        }
        $data = $_POST;
        $data['create_time'] = time();
        if ($id = Db::name('ad_position')->insertGetId($data)) {
            $this->success('添加广告位成功！');
        } else {
            $this->error('添加广告位失败！');
        }
    }

    public function edit()
    {
        if ($_POST) {
            $validate = new Validate([
                ['name', 'require|unique:ad_position', '广告位置必填|广告位置重复'],
                ['width', 'require', '广告宽度必填'],
                ['height', 'require', '广告高度必填'],
            ]);
            if (!$validate->check($_POST)) {
                $this->error($validate->getError());
            }
            $data = $_POST;
            $data['update_time'] = time();
            if ($id = Db::name('ad_position')->update($data)) {
                $this->success('添加广告位成功！');
            } else {
                $this->error('添加广告位失败！');
            }
        } else {
            $list = Db::name('ad_position')
                ->find(array('id' => input('id')));
            $map = array(
                'data' => $list
            );
            return view('edit', $map);
        }
    }


    public function del()
    {

        if (Db::name('ads')->where(array('place' => input('id')))->find()) {
            $this->error('当前广告位仍有广告，请谨慎删除！');
        }
        if (Db::name('ad_position')->delete(input('id'))) {
            $this->success('当前分类删除成功', url('admin/ads/index'));
        } else {
            $this->error('当前分类删除失败');
        }

    }

}